<?php

require_once '../config/server.inc.php';
require_once '../inc/functions.inc.php';


if (isset($_GET['q'])&&(strpos($_GET['q'], '.')===false)) {

	$arr = explode("/", $_GET['q']);
	list($action, $settings) = $arr;
	array_shift($arr);
	array_shift($arr);
	$folders = (count($arr)==0) ? "" : "/".implode("/", $arr);

	$user = $_SERVER['REMOTE_USER'];
	$basepath = "{$setting['base']}/settings/{$setting['secretfolder']}";

	if ($action=='list') {
		$res = array();
		$path = "{$basepath}/{$user}{$folders}";
		if (is_dir($path)) {
			$arr = array_diff(scandir("{$path}"), array('.','..'));
			foreach ($arr as $file) if (is_file("{$path}/{$file}")) $res[] = str_replace(".inc", "", $file);
		}
		echo json_encode($res);
		exit;
	}

	if ($action=='open') {
		$filename = "{$basepath}/{$user}{$folders}/{$settings}.inc";
		if (is_file($filename)) include_once "{$filename}";
		exit;
	}

	// POST `json` is geldige JSON string.
	// Vanaf versie 5.4 kan die mooi gemaakt worden.
	if ((($action=='save')||($action=='merge'))&&(isset($_POST['json']))) {
		$post = json_decode("{$_POST['json']}", true);
		$path = "{$basepath}/{$user}{$folders}";
		if (!file_exists($path)) mkdir($path, 0700, true);
		if (is_file("{$path}/{$settings}.inc")&&($action=='merge')) {
			$file = file_get_contents("{$path}/{$settings}.inc");		
			$file = json_decode("{$file}", true);
			$post = extend($file, $post);
		}
		$data = (PHP_VERSION_ID > 50399) ? json_encode($post, JSON_PRETTY_PRINT) : json_encode($post);
		file_put_contents("{$path}/{$settings}.inc", $data);
		exit;
	}
}

?>
<form action="/compare/settings/merge/gasflesopslag" method="post">
 <input type="text" name="json" value='{"compare":{"dbb":{"prefix":"mooie-prefix"}}}' />
 <input type="submit" name="submit" value="stuur" />
</form>


echo "<h2>Nothing</h2>";
echo "<pre>";
echo "<b>File</b>";
print_r ($file);
echo "<b>POst</b>";
print_r ($post);
print_r ($_GET);
print_r ($_POST);
echo "</pre>";